package com.hmdp.service.impl;

import com.hmdp.domain.dto.Result;
import com.hmdp.domain.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisGenerateID;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Range;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private SeckillVoucherServiceImpl seckillVoucherService;
    //redis实现的全局唯一ID生成器
    @Autowired
    private RedisGenerateID redisGenerateID;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //redis分布式锁的名称
    private static final String REDIS_KEY_NAME = "VoucherOrder:";
    //redis分布式锁的过期时间
    @Value("${hmdp.redislock.timeout}")
    private long redisTimeout;
    //redis分布式锁的过期时间单位
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
    //lua脚本
    private static final DefaultRedisScript<Long> REDIS_SCRIPT;
    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    //消费者，处理消费任务
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newFixedThreadPool(9);
    private IVoucherOrderService proxy;//this

    static {
        REDIS_SCRIPT = new DefaultRedisScript<>();
        REDIS_SCRIPT.setLocation(new ClassPathResource("seckillVoucherOrder.lua"));
        REDIS_SCRIPT.setResultType(Long.class);
    }

    /**
     * 消息队列消费者
     */
    @Async("orderConsumerThreadPool")
    public void consumer() {
        while (true) {
            try {
                List<ObjectRecord<String, VoucherOrder>> recordList =
                        stringRedisTemplate.opsForStream().read(VoucherOrder.class, Consumer.from(VOUCHER_ORDER_TASK_CONSUMER_GROUP, VOUCHER_ORDER_TASK_CONSUMER_NAME),
                                StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                                StreamOffset.create(VOUCHER_ORDER_TASK, ReadOffset.lastConsumed()));
                if (recordList == null || recordList.isEmpty()) {
                    //如果为空继续循环
                    break;
                }
                //进行下单
                ObjectRecord<String, VoucherOrder> entries = handleOrder(recordList);
                //确认消息
                stringRedisTemplate.opsForStream().acknowledge(VOUCHER_ORDER_TASK, VOUCHER_ORDER_TASK_CONSUMER_GROUP, entries.getId());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("错误信息{}", e.getMessage());
                //处理异常消息
                handlePendingList();
            }
        }
    }

    private ObjectRecord<String, VoucherOrder> handleOrder(List<ObjectRecord<String, VoucherOrder>> recordList) {
        ObjectRecord<String, VoucherOrder> record = recordList.get(0);
        VoucherOrder order = record.getValue();
        //创建订单
        proxy.save(order);
        log.info("订单处理完毕:{}", order.getVoucherId());
        return record;
    }

    /**
     * 处理异常订单
     */
    private void handlePendingList() {
        while (true) {
            List<ObjectRecord<String, VoucherOrder>> recordList = stringRedisTemplate.opsForStream().read(
                    VoucherOrder.class,
                    Consumer.from(VOUCHER_ORDER_TASK_CONSUMER_GROUP, VOUCHER_ORDER_TASK_CONSUMER_NAME),
                    StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                    StreamOffset.create(VOUCHER_ORDER_TASK, ReadOffset.from("0")));
            if (recordList == null || recordList.isEmpty()) {
                break;
            }
            ObjectRecord<String, VoucherOrder> entries = recordList.get(0);
            //死信处理
            PendingMessages pending = stringRedisTemplate.opsForStream().pending(
                    entries.getStream(),
                    VOUCHER_ORDER_TASK_CONSUMER_GROUP,
                    Range.unbounded(),
                    10);
            for (PendingMessage pendingMessage : pending) {
                stringRedisTemplate.opsForStream().delete(entries.getStream(), pendingMessage.getId());
            }
            //进行下单
            ObjectRecord<String,VoucherOrder> record = handleOrder(recordList);
            stringRedisTemplate.opsForStream().acknowledge(VOUCHER_ORDER_TASK, VOUCHER_ORDER_TASK_CONSUMER_GROUP, record.getId());
        }
    }


    /**
     * 在类构造出来后开启子线程
     */
    @PostConstruct
    private void init() {
        proxy = this;
        consumer();
    }

    /***
     * 使用消息队列的方式进行秒杀下单
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        Long result = stringRedisTemplate.execute(REDIS_SCRIPT,
                Collections.emptyList(),
                SECKILL_STOCK_KEY + voucherId.toString(), userId.toString(), BUY_VOUCHER_USER_ID + voucherId);
        int r = result.intValue();
        //判断是否有资格
        if (r != 0) {
            return r == 1 ? Result.fail("库存不足") : Result.fail("每个用户只能购买一次");
        }
        //生成订单
        Long voucherOrderId = redisGenerateID.generateId();//订单id
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(voucherOrderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        //向redis消息队列中发布消息
        ObjectRecord<String, VoucherOrder> objectRecord = ObjectRecord.create(VOUCHER_ORDER_TASK, voucherOrder);
        stringRedisTemplate.opsForStream().add(objectRecord);
        consumer();


        return Result.ok(voucherOrderId);
    }


}
